package evolution;

import java.io.IOException;
import java.util.UUID;

import evolution.changelog.ChangeLogEntry;


public class VersionedResource
{
	public static final String CHANGE_LOG = "ChangeLog.txt";

	private UUID uuid;

	private final String name;
	private final String parent;
	private long lastModifiedTime;

	private final VersionedResourceLookup versionedResourceLookup;

	public VersionedResource(Directory dir, VersionedResourceLookup versionedResourceLookup) throws ResourceException, VersionedDirectoryTreeException
	{
		this.versionedResourceLookup = versionedResourceLookup;
		uuid = UUID.fromString(dir.getName());
		File file = (File) dir.getMember(CHANGE_LOG);
		if (file == null)
		{
			throw new VersionedDirectoryTreeException("Missing file: " + CHANGE_LOG);
		}
		ChangeLogReader changeLogReader = new ChangeLogReader(file.getReader());
		ChangeLogEntry entry;
		try
		{
			entry = changeLogReader.nextEntry();
		}
		catch (IOException e)
		{
			throw new ResourceException("Failed to get next change log entry", e);
		}
		if (entry == null)
		{
			throw new IllegalStateException(CHANGE_LOG + " was not properly initialized, does not contain a single entry");
		}
		name = entry.getFieldValue("Name");
		parent = entry.getFieldValue("Parent");
		lastModifiedTime = Long.parseLong(entry.getFieldValue("Date"));
	}

	public String getPath()
	{
		VersionedResource parent = getParent();
		if (parent == null)
		{
			return name;
		}
		else
		{
			if (parent.getPath() == null)
			{
				return name;
			}
			else
			{
				String parentPath = parent.getPath();
				if (parentPath.equals("/"))
				{
					return parentPath + name;
				}
				else
				{
					return parentPath + "/" + name;
				}
			}
		}
	}

	public VersionedResource getParent()
	{
		if (parent == null)
		{
			return null;
		}
		VersionedResource el = versionedResourceLookup.lookupElement(UUID.fromString(parent));
		if (el == null)
		{
			throw new IllegalStateException();
		}
		return el;
	}

	public UUID getUUID()
	{
		return uuid;
	}

	public long getLastModifiedTime()
	{
		return lastModifiedTime;
	}

	@Override
	public String toString()
	{
		return "[" + getUUID() + ":" + getPath() + "]";
	}

}
